#-*- encoding: utf-8 -*-
import win32com.client 
from Misc.Utils import *

from DataAccess.QueryBlp import *

from datetime import date,timedelta

from ReportTool.HldReport import *
from ReportTool.PnLReport import *
from ReportTool.NAVReport import *
from ReportTool.MktValReport import *
from ReportTool.TradeReport import *
from ReportTool.RealizedPnL import *
from ReportTool.OnshoreHldReport import *

from Config.ReportConfig import *

def Monthly_Data_Collection(ref_date, portf_id):

	tplt_file = TPLT_PATH + 'Monthly Data Collection.xls'
	xApp = win32com.client.Dispatch("Excel.Application")
	xBook = xApp.Workbooks.Open(tplt_file)
	xSht = xBook.Worksheets('Report')
	
	d = date(2008, 6, 30)
	row = 2
	
	while d <= ref_date:
	
		hld = query_hld(d, portf_id)
		pnl = query_pnl(date(d.year, d.month, 1), d, portf_id)
		
		expo = {} # expo[(ticker, l/s)] = mkt_exposure
		for elem in hld:
			expo[(elem[0], elem[3])] = elem[12]
		
		blp_tick = []
		blp_eq_tick = []
		rcd = {}

		for elem in pnl:	
			ticker = elem[0]
			sec_type = elem[2]
			long_short = elem[3]
			ret = elem[6]
			trd_curncy = elem[7]
			base_curncy = elem[8]
			exp = expo[(ticker, long_short)] if expo.has_key((ticker, long_short)) else 0
			last_price = query_latest_price(d, ticker)
			
			#blp ticker
			blp_ticker = ticker
			if (sec_type == 'PNOTE') or (sec_type == 'STOCK' and trd_curncy == 'CNY'):
				blp_ticker = ch_ticker_to_blp_ticker(ticker)
			if (sec_type == 'STOCK' and trd_curncy == 'HKD') and ticker != 'CITINQ' and ticker != 'TCCTMQ':
				blp_ticker = hk_ticker_to_blp_ticker(ticker)
			
			blp_tick.append(blp_ticker)
			if is_equity(blp_ticker):
				blp_eq_tick.append(blp_ticker)
				
			rcd[(blp_ticker, long_short)] = [exp, ret, last_price, base_curncy, sec_type]
		
		#sec_name_dict = query_blp_static(blp_tick, ['NAME'])
		sec_curncy_dict = query_blp_static(blp_tick, ['CRNCY'])
		sec_sector_dict = query_blp_static(blp_eq_tick, ['GICS_SECTOR_NAME'])
		mkt_cap_dict = query_blp_latest(blp_eq_tick, ['CUR_MKT_CAP'], d)
		
		for elem in rcd.keys():
			tick = elem[0]
			long_short = elem[1]
			exp = rcd[elem][0] 
			ret = rcd[elem][1]
			last_price = rcd[elem][2] 
			base_curncy = rcd[elem][3]
			sec_type = rcd[elem][4]
			#sec_name = sec_name_dict[tick]['NAME']
			local_curncy = sec_curncy_dict[tick]['CRNCY']
			fx = query_latest_fx(d, base_curncy, local_curncy) if local_curncy != 'NA' else 'NA'
			gics_name = sec_sector_dict[tick]['GICS_SECTOR_NAME'] if sec_sector_dict.has_key(tick) else 'Others'
					
			if mkt_cap_dict.has_key(tick) and fx != 'NA':
				mktcap_local = mkt_cap_dict[tick]['CUR_MKT_CAP']
				mktcap_base = mktcap_local / fx if mktcap_local != 'NA' else 'NA'
			else:
				mktcap_local = 'Others'
				mktcap_base = 'Others'
			
			xSht.Range(xSht.Cells(row, 1), xSht.Cells(row, 13)).Value = (d, tick, '', sec_type, exp, ret, long_short,
			mktcap_local, mktcap_base, last_price, local_curncy, fx, gics_name)
			
			row += 1
			
		print '   running info, data collection completed at ', d.isoformat()
		d = end_of_mth(d, 1)
		
	rept_file = REPT_PATH + 'Monthly Data Collection.xls'
	xBook.SaveAs(rept_file)
	xBook.Close()
	del xApp
	
	print 'info, monthly data collection completed'		